// component/com-scroll-content/com-scroll-content.js
const computedBehavior = require('miniprogram-computed')

Component({
  behaviors: [computedBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    emptyBox: { //是否采用自定义的无数据提示组件
      type: Boolean,
      default: false
    }
  },
  options: {
    styleIsolation: 'apply-shared',
    addGlobalClass: true,
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },

  /**
   * 组件的初始数据
   */
  data: {
    hasData: false,
    pageSize: 20,
    currentPage: 1,
    pageMax: 1,
    isLoading: false,
    apiFetch: null, //请求数据方法（外部传入）
    bottomBase: true,
    emptyTips: "",
  },

  computed: {
    isHidden(data) {
      return data.hasData || data.isLoading
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 滚动加载更多
    visitorScroolEvent() {
      let nextPage = this.data.currentPage + 1
      if (nextPage > this.data.pageMax) {
        console.log("none");
        this.setData({
          bottomBase: false
        })

        return
      }

      this.setData({
        bottomBase: true
      })
      this.fetchHouse(nextPage)
    },

    fetchHouse(page, apiFetch) {
      if (this.data.isLoading) return
      this.data.apiFetch = apiFetch || this.data.apiFetch

      if (!this.data.apiFetch) {
        console.log("未传 apiFetch");
        
        return 
      }
      if (page == 1) {
        this.data.currentPage = 1
        this.data.pageMax = 1
      }

      this.setData({
        isLoading: true,
        bottomBase: true
      })

      let p1 = new Promise((resolve, reject) => {
        setTimeout(resolve, 800)
      })
      let p2 = this.data.apiFetch({
        page,
        pageSize: this.data.pageSize,
      })

      Promise.all([p1, p2])
        .then((res) => {
          let data = res[1]
          data.content = data.content || {}
          if (!data.hasOwnProperty('isSuccess')) {
            data.isSuccess = true
          }
          if (!data.isSuccess) {
            return Promise.reject(data.errorMessage)
          }
          // total 总页数 
          let { page, rows, total, pageSize } = data.content
          rows = rows || []
          this.data.currentPage = page
          
          // stupid (某些接口不规范 )
          if (data.stupid) {
            this.data.pageMax = rows.length < (pageSize || this.data.pageSize) ? page : 999
          } else {
            this.data.pageMax = total
          }

          this.setData({
            isLoading: false,
            hasData: (rows && rows.length),
            emptyTips: data.errorCode ? data.successMessage : "暂无数据"
          })
          
          data.handleData && data.handleData(rows)
          this.triggerEvent("onscrollapi", rows)
        })
        .catch((error) => {
          this.setData({
            isLoading: false,
            hasData: false
          })
        })
    },

    
  }
})